﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.MODEL.NewProductBigPic;

using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using MINERP.COM;
using MINERP.MODEL.FoundationModel;
using MINERP.COM.DBHelper;

namespace MINERP.DAL.NewMakeBigPic
{
    /// <summary>
    /// 生成大图的主要数据库访问类
    /// </summary>
    public class MainDAL
    {
        /// <summary>
        /// 取得要生成大图的大板信息，同时也被分配了格子信息
        /// </summary>
        /// <returns></returns>
        public BoardInfo_ProductBigPic GetOneBoardToMake(int makePicNo)
        {
            int hasEmptyGrid = 0;
            BoardInfo_ProductBigPic resultBoard;

            List<PhotoInfo_ProductBigPic> plist = new List<PhotoInfo_ProductBigPic>();
            Board_Info boardBaseInfo = new Board_Info();

            Database db = DatabaseFactory.CreateDatabase();
           
            {
               
                DbCommand dbCommand = db.GetStoredProcCommand("GetProductBigPicBoard2");

                db.AddInParameter(dbCommand, "@makePicNo", DbType.Int32, makePicNo);
                db.AddOutParameter(dbCommand, "@boardId", DbType.Int32, 4);
                db.AddOutParameter(dbCommand, "@bigDPI", DbType.Int32, 4);
                db.AddOutParameter(dbCommand, "@bigPicPath", DbType.String, 200);
                db.AddOutParameter(dbCommand, "@bigWidth", DbType.Int32, 4);
                db.AddOutParameter(dbCommand, "@bigHeight", DbType.Int32, 4);
                db.AddOutParameter(dbCommand, "@hasEmptyGrid", DbType.Int16, 1);
                db.AddOutParameter(dbCommand, "@isTransverse", DbType.Int16, 1);
                db.AddOutParameter(dbCommand, "@iccPath", DbType.String, 100);
                db.AddOutParameter(dbCommand, "@AddSharpen", DbType.Int32, 4);
                db.AddOutParameter(dbCommand, "@PrintName", DbType.String, 200);
                db.AddOutParameter(dbCommand, "@CutFlagFrontOrBehind", DbType.Int16, 1);
                db.AddOutParameter(dbCommand, "@BoardType", DbType.Int16, 1);
                db.AddOutParameter(dbCommand, "@IsAutoCut", DbType.Int16, 1);
             
                try
                {
                    using (IDataReader dr = db.ExecuteReader(dbCommand))
                    {
                        while (dr.Read())
                        {
                            string tempphotoRemarkStr = dr["photoRemark"].ToString();
                            string remark = tempphotoRemarkStr;

                            //string [] remarkArray = tempphotoRemarkStr.Split('\\');
                            //if (remarkArray.Length > 1)
                            //{
                            //    for (int i = remarkArray.Length - 2; i < remarkArray.Length; i++)
                            //    {
                            //        remark += remarkArray[i]+"\\";
                            //    }
                            //    remark = remark.TrimEnd('\\');
                            //}
                            int factBarCodeStatus = 0;
                            int dbBarCodeStatus = dr.GetInt32(12);
                            if (dbBarCodeStatus == 0)
                            {
                                factBarCodeStatus = 1;
                            }
                            else if (dbBarCodeStatus == 1)
                            {
                                factBarCodeStatus = 0;
                            }
                            else
                            {
                                factBarCodeStatus = dbBarCodeStatus;
                            }
                            PhotoInfo_ProductBigPic pi = new PhotoInfo_ProductBigPic();
                            pi = new PhotoInfo_ProductBigPic()
                            {
                                PhotoId = dr.GetInt32(2),
                                OrderProductId = dr.GetInt32(3),
                                PhotoName = dr.GetString(4),
                                Width = dr.GetDouble(5),
                                Height = dr.GetDouble(6),
                                PixWidth = dr.GetInt32(7),
                                PixHeight = dr.GetInt32(8),
                                PicPath = dr.GetString(9),
                                IsClearBox = dr.GetInt32(10),
                                IsWhirl = dr.GetBoolean(11),
                                BarCodeStatus = factBarCodeStatus,
                                OrderProductName = dr.GetString(13),
                                CtmName = dr.GetString(14),
                                OrderRemark = dr.GetString(15),
                                Priority = dr.GetInt32(16),
                                ShopName = dr.GetString(17),
                                GridName = dr.GetString(18),
                                PicMakeUpId = dr.GetInt32(19),
                                //X = dr.GetString(0),
                                //Y = dr.GetString(1),
                                //Remark = dr["photoRemark"].ToString(),
                                Remark = remark,
                                labelWidth = Convert.ToInt32(dr["labelWidth"].ToString()),
                                Location = new Point(Convert.ToInt32(dr.GetString(0)), Convert.ToInt32(dr.GetString(1)))//如果不要加密就用这句 };,
                                ,
                                NumInOrder =   Convert.ToString(dr["NumInOrder"] is DBNull ? "" : dr["NumInOrder"])

                            };

                            pi.DXFFilePath = Convert.ToString(dr["DXFFilePath"] is DBNull ? "" : dr["DXFFilePath"]);
                            pi.DXFContent = dr["DXFContent"] is DBNull ? null : (byte[])(dr["DXFContent"]);
                            plist.Add(pi);
                        }
                        dr.Close();
                        
                        boardBaseInfo.BoardId = Convert.ToInt32(db.GetParameterValue(dbCommand, "@boardId"));

                        if (plist.Count < 1)//如果只有大板信息没有小图片信息，则删除大板信息
                        {
                            //DbCommand dbCmd_DelBoardByBoarId=db.get
                            db.ExecuteNonQuery(CommandType.Text, string.Format("delete board where boardid={0}", boardBaseInfo.BoardId));
                            return null;
                        }
                        hasEmptyGrid = Convert.ToInt32(db.GetParameterValue(dbCommand, "@hasEmptyGrid"));
                        hasEmptyGrid = 1;
                        if (1 == 1)
                        {

                            if (boardBaseInfo.BoardId == 0)
                            {
                                return null;
                            }
                            boardBaseInfo.DPI = Convert.ToInt32(db.GetParameterValue(dbCommand, "@bigDPI"));
                            boardBaseInfo.PicPath = Convert.ToString(db.GetParameterValue(dbCommand, "@bigPicPath"));
                            boardBaseInfo.PixWidth = Convert.ToInt32(db.GetParameterValue(dbCommand, "@bigWidth"));
                            boardBaseInfo.PixHeight = Convert.ToInt32(db.GetParameterValue(dbCommand, "@bigHeight"));
                            boardBaseInfo.IsTransverse = Convert.ToBoolean(db.GetParameterValue(dbCommand, "@isTransverse"));
                            boardBaseInfo.IccPath = Convert.ToString(db.GetParameterValue(dbCommand, "@iccPath"));
                            boardBaseInfo.Sharpen = Convert.ToInt32(db.GetParameterValue(dbCommand, "@AddSharpen"));
                            boardBaseInfo.PrintName = Convert.ToString(db.GetParameterValue(dbCommand, "@PrintName"));
                            boardBaseInfo.CutFlagFrontOrBehind = Convert.ToInt32(db.GetParameterValue(dbCommand, "@CutFlagFrontOrBehind"));
                            boardBaseInfo.IsAutoCut = Convert.ToBoolean(db.GetParameterValue(dbCommand, "@IsAutoCut"));
                                    
                            var BoardType = db.GetParameterValue(dbCommand, "@BoardType");
                            if (BoardType is DBNull)
                            {
                                boardBaseInfo.BoardProcudtType = 0;
                            }
                            else
                            {
                                boardBaseInfo.BoardProcudtType = Convert.ToInt32(db.GetParameterValue(dbCommand, "@BoardType"));
                            }

                        }
                        else//如果没有可用的格子就返回NULL 
                        {
                            return null;
                        }
                    }
                }
                catch (SqlException ex)
                {
                    WriteLogForCheck.WriteLogFile(ex.ToString());
                    //result = -2;//代表从数据库取数据出错
                }
                finally
                {
                    if (dbCommand.Connection.State != ConnectionState.Closed)
                    {
                        dbCommand.Connection.Close();
                    }
                }

                resultBoard = new BoardInfo_ProductBigPic() { BoardBaseInfo = boardBaseInfo, ListPhotos = plist };
            }
            return resultBoard;

        }

        /// <summary>
        /// 生成大图成功后更改大图的状态以及照片的状态还有流程的状态
        /// </summary>
        /// <param name="BoardId"></param>
        /// <returns>输出结果1:代表正常,-1:大板存在，-2：照片不存在；-3：执行操作时出错</returns>
        public int MakeBigPicSusscess(int BoardId, string newPicPath)
        {
            int result = 1;
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("MakeBigPicSuccess");

            db.AddInParameter(dbCommand, "boardId", DbType.Int32, BoardId);
            db.AddOutParameter(dbCommand, "outResult", DbType.Int32, 4);
            db.AddInParameter(dbCommand, "newPicPath", DbType.String, newPicPath);

            try
            {
                db.ExecuteNonQuery(dbCommand);
                result = Convert.ToInt32(db.GetParameterValue(dbCommand, "outResult"));
            }
            catch (Exception)
            {
                result = -3;
            }

            return result;

        }

        public int SetBoardStatus(int boardID, int status, string remark)
        {
            int iRet = 1;
            Database db = null;
            try
            {
                db = DatabaseFactory.CreateDatabase();
                string sqlText = "";
                sqlText = "update board set status= " + status + ", Remark='" + remark + "' where boardID=" + boardID;

                DbCommand dbCommand = db.GetSqlStringCommand(sqlText);
                db.ExecuteNonQuery(dbCommand);
            }
            catch
            {
                iRet = -1;
                return iRet;
            }
            return iRet;
        }
        public void SetBoardAutoCutInfo(int inBoardid, string inStr)
        {
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                Board bd = db.Board.FirstOrDefault(b => b.BoardId == inBoardid);
                bd.AutoPoint = inStr;
                db.SaveChanges();
            }
 
        }
    }
}
